import { IFeidaoAiBrowserComponent } from '@dfeidao/atom-web/interfaces';

import get from '@dfeidao/atom-web/local/get';
import remove from '@dfeidao/atom-web/local/remove';
import fire from '@dfeidao/atom-web/msg/fire';
import nodejs from "@dfeidao/atom-web/msg/nodejs";
import error from '@dfeidao/atom-web/msgbox/error';
import success from '@dfeidao/atom-web/msgbox/success';
import s_get from '@dfeidao/atom-web/storage/get';

export default async function a002(fd: IFeidaoAiBrowserComponent) {
	//  保存
	const _id = get(fd, '_id');
	// const user = await whoami(get_user_info);
	// console.log(user)
	const prid = await s_get('productid');
	const usercode = get(fd, 'ucode');
	const create_time = new Date().getTime();
	const role_no = fd.data.node.querySelector<HTMLInputElement>('#name2').value;
	const role_no5 = get(fd, 'r_no');// 父窗体传入
	const staff_name = fd.data.node.querySelector<HTMLInputElement>('#name').value;
	const staff_no_wk = fd.data.node.querySelector<HTMLInputElement>('#name').getAttribute('data-feidao-wid');
	// console.log(staff_name, staff_no_wk, '--------------------------', role_no, role_no5);
	if (!role_no) {
		const query = {
			_id,
			usercode,
			role_no: role_no5,
			pk_val: staff_no_wk,
			search_field_val: staff_name,
			create_time,
			productid: prid
		};
		const res = await nodejs('consumer/zj-000006/consumer-upd2', query);
		if (res === 'success') {
			fire('zj-000004', 'ec-002', usercode);
			remove(fd, 'staff_no');
			remove(fd, 'role_no');
			success('保存成功');
		} else {
			error('保存失败');
		}
	} else {
		if (role_no !== role_no5) {
			const query2 = {
				filter: {
					productid: prid,
					usercode,
					role_no
				}
			};
			const res2 = await nodejs<{ dataArray: object[] }>("consumer/zj-000006/consumer-find4", query2);
			// console.log(res2);
			if (res2.dataArray.length > 0) {
				error('角色已被关联');
				return;
			} else {
				const query = {
					_id,
					usercode,
					role_no,
					pk_val: staff_no_wk,
					search_field_val: staff_name,
					create_time,
					productid: prid
				};
				const res = await nodejs('consumer/zj-000006/consumer-upd2', query);
				if (res === 'success') {
					fire('zj-000004', 'ec-002', usercode);
					remove(fd, 'staff_no');
					remove(fd, 'role_no');
					fd.data.node.classList.add('display-n');
					success('保存成功');
				} else {
					error('保存失败');
				}
			}
		} else {
			const query = {
				_id,
				usercode,
				role_no,
				pk_val: staff_no_wk,
				search_field_val: staff_name,
				create_time,
				productid: prid
			};
			const res = await nodejs('consumer/zj-000006/consumer-upd2', query);
			if (res === 'success') {
				fire('zj-000004', 'ec-002', usercode);
				remove(fd, 'staff_no');
				remove(fd, 'role_no');
				fd.data.node.classList.add('display-n');
				success('保存成功');
			} else {
				error('保存失败');
			}
		}
	}
}
